package com.tevintao.marketingsystem.activity;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.tevintao.marketingsystem.R;
import com.tevintao.marketingsystem.commen.UrlConfig;
import com.tevintao.marketingsystem.log.LogManager;
import com.tevintao.marketingsystem.provider.ContactsManager;
import com.tevintao.marketingsystem.services.AccountManager;
import com.tevintao.marketingsystem.tool.SystemPathTool;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class ActContactsImport extends AppCompatActivity implements View.OnClickListener {

    private EditText mInputNum;
    private Button mStartImport;
    private Button mRefresh;
    private Button mClear;
    private RequestQueue queue = null;

    private String mAccount;

    private ListView mListView;

    private ArrayList<String> mName = new ArrayList<>();
    private ArrayList<String> mPhones = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        queue = Volley.newRequestQueue(this);
        setContentView(R.layout.activity_contacts_import);
        mInputNum = (EditText) findViewById(R.id.contacts_number);
        mStartImport = (Button) findViewById(R.id.contacts_import);
        mRefresh = (Button) findViewById(R.id.contacts_refresh);
        mRefresh.setOnClickListener(this);
        mClear = (Button) findViewById(R.id.contacts_clear);
        mClear.setOnClickListener(this);

        mStartImport.setOnClickListener(this);
        mListView = (ListView) findViewById(R.id.contacts_list);
//        AccountManager.getInstance(this)
        mListView.setAdapter(mContactsAdapter);

        new Thread(new Runnable() {
            @Override
            public void run() {
                String newDataPath = AccountManager.MM_DATA_ROOT + "/" + AccountManager.ACCOUNT_NAME_FILE_NAME;
                mAccount = SystemPathTool.getOutPutContent(newDataPath);
                if (!TextUtils.isEmpty(mAccount)) {
                    getWindow().getDecorView().post(new Runnable() {
                        @Override
                        public void run() {
                            setTitle(mAccount);
                        }
                    });
                }
            }
        }).start();

    }

    @Override
    protected void onPostResume() {
        super.onPostResume();

    }

    @Override
    public void onClick(View v) {
        if (v == mStartImport) {
            int num = 0;
            try {
                num = Integer.parseInt(mInputNum.getText().toString());
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            if (num > 0 && num < 100) {
                getContacts(num);
            } else if (num >= 100) {
                Toast.makeText(this, "数量不能超过100", Toast.LENGTH_LONG).show();
            }
        } else if (v == mRefresh) {
            Cursor cursor = ContactsManager.getInstance().queryAll(mAccount);
            while (cursor.moveToNext()) {
                mName.add(cursor.getString(cursor.getColumnIndex("display_name")));
                mPhones.add(cursor.getString(cursor.getColumnIndex("data1")));
                LogManager.getInstance().logInfo(cursor.getString(cursor.getColumnIndex("data1")));
            }
            mContactsAdapter.notifyDataSetChanged();
        } else if (v == mClear) {

            Toast.makeText(this, "清理通讯录 = " + ContactsManager.getInstance().clearDb(), Toast.LENGTH_SHORT).show();
        }
    }


    private JsonObjectRequest mReportJson;
    private int insertNum = 0;

    public void getContacts(int num) {
        if (TextUtils.isEmpty(mAccount)) {
            Toast.makeText(this, "当前没有帐号，请切换到指定帐号后，在添加通讯录!", Toast.LENGTH_SHORT).show();
            return;
        }

        JSONObject jo = new JSONObject();


        String url = String.format(UrlConfig.URL_GET_CONTACTS, num,mAccount);
        LogManager.getInstance().logInfo("url = " + url);
        mReportJson = new JsonObjectRequest(url, jo, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(final JSONObject jsonObject) {
                LogManager.getInstance().logInfo(jsonObject.toString());
                insertNum = 0;
                try {
                    if (jsonObject.has("code") && jsonObject.getInt("code") == 0) {
                        JSONArray ja = jsonObject.getJSONArray("date");
                        for (int i = 0; i < ja.length(); i++) {
                            LogManager.getInstance().logInfo(ja.get(i).toString());
                            JSONObject jo = ja.getJSONObject(i);
                            String name = "";
                            String phone = "";
                            if (jo.has("name")) {
                                name = jo.getString("name");
                            }
                            if (jo.has("number")) {
                                phone = jo.getString("number");
                            }
                            boolean inserted = ContactsManager.getInstance().insertContacts(mAccount, name, phone);
                            LogManager.getInstance().logInfo("insert " + inserted + " name = " + name + " phone = " + phone);
                            insertNum++;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mStartImport.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ActContactsImport.this, "插入通讯录数量 =  " + insertNum, Toast.LENGTH_LONG).show();

                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(final VolleyError error) {


                mStartImport.post(new Runnable() {
                    @Override
                    public void run() {
                        if (null != error && error.getMessage() != null) {
                            LogManager.getInstance().logError("获取通讯录错误 =  " + error.getMessage());
                            Toast.makeText(ActContactsImport.this, "获取通讯录错误 =  " + error.getMessage(), Toast.LENGTH_LONG).show();
                        } else {
                            LogManager.getInstance().logError("获取通讯录错误 msg = null " + error.toString());
                        }
                    }
                });


            }
        });
        mReportJson.setRetryPolicy(new DefaultRetryPolicy(30 * 1000, 1, 1.0f));

        queue.add(mReportJson);
    }

    private BaseAdapter mContactsAdapter = new BaseAdapter() {
        @Override
        public int getCount() {
            return mPhones.size();
        }

        @Override
        public Object getItem(int position) {
            return mPhones.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView tv = new TextView(ActContactsImport.this);
            tv.setTextSize(30);
            tv.setText(mName.get(position) + " - " + mPhones.get(position));
            return tv;
        }
    };
}
